package com.springboot.frame.socket.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.net.InetSocketAddress;
import lombok.extern.slf4j.Slf4j;
/**
 * @ClassName: NettyClinet
 * @Author: huangzf
 * @Date: 2018/9/25 15:26
 * @Description:
 */
@Slf4j
public class ClinetNetty {

    private String host = "localhost";
    private int port = 9000;
    private Channel channel = null;

    public ClinetNetty(){

    }

    public ClinetNetty(String host, int port) {
        this.host = host;
        this.port = port;
    }



    public  void start()  {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            // 注册线程池
            b.group(group)
                    // 使用NioSocketChannel来作为连接用的channel类
                    .channel(NioSocketChannel.class)
                    // 绑定连接端口和host信息
                    .remoteAddress(new InetSocketAddress(this.host, this.port))
                    // 绑定连接初始化器
                    .handler(new ClientChannelInitializer(this.host, this.port));
            log.info("连接服务端成功..");
            // 异步连接服务器
            ChannelFuture channelFuture = b.connect().sync();
            channel = channelFuture.channel();
            channel.writeAndFlush("ffffffffffffffffffffffffff");
            //等待服务端监听端口关闭
            channel.closeFuture().sync();

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new ClinetNetty("127.0.0.1",9000).start();
    }
}
